package cn.bdqn.sharedpreferences01;

import android.app.Activity;
import android.content.SharedPreferences;
import android.support.annotation.RequiresPermission;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private EditText etUserName,etPassword;
    private CheckBox cbRemeber;
    private Button btnLogin;
    private final String fileName="userinfo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        read();
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                write();
            }
        });
    }
    /**
     * 读取存放的数据
     */
    private void read(){
     SharedPreferences sharedPreferences=getSharedPreferences(fileName,Activity.MODE_PRIVATE);
     String userName=sharedPreferences.getString("userName","");
        String password=sharedPreferences.getString("password","");
       boolean remeber=sharedPreferences.getBoolean("remeber",false);
         if (remeber){
             etUserName.setText(userName);
             etPassword.setText(password);
             cbRemeber.setChecked(remeber);


         }
    }

    @Override
    protected void onPause() {
        super.onPause();
        write();
    }

    /**
     * 讲键值对存放在SharePerfence
     */
    private void write(){
        //1.获取sharePerfence接口对象
        SharedPreferences sharedPreferences = getSharedPreferences(fileName, Activity.MODE_PRIVATE);
        //2.获取edit接口对象
        SharedPreferences.Editor editor=sharedPreferences.edit();
        //3.保存键值对象
        if (cbRemeber.isChecked()){
            editor.putString("userName",etUserName.getText().toString());
            editor.putString("password",etPassword.getText().toString());
            editor.putBoolean("remeber",cbRemeber.isChecked());
        }else{
            editor.putString("userName","");
            editor.putString("password","");
            editor.putBoolean("remeber",cbRemeber.isChecked());
        }
        //4提交
        editor.commit();
        Toast.makeText(this, "提交成功", Toast.LENGTH_SHORT).show();

    }
    private void initview(){
        etUserName=findViewById(R.id.et_username);
        etPassword=findViewById(R.id.et_password);
        cbRemeber=findViewById(R.id.cb_remeber);
        btnLogin=findViewById(R.id.btn_login);

    }
}

